package com.ruoyi.web.controller.byd;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.domain.MaterialCutting.LaserModule;
import com.ruoyi.system.domain.MaterialCutting.LayoutModule;
import com.ruoyi.system.domain.MaterialCutting.SortingModule;
import com.ruoyi.system.mapper.LaserModuleMapper;
import com.ruoyi.system.mapper.LayoutModuleMapper;
import com.ruoyi.system.mapper.SortingModuleMapper;
import com.ruoyi.util.ExtractFile;
import com.ruoyi.util.SnowflakeIdGenerator;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/pdf")
public class PdfProcessingController {

    @Autowired
    private LayoutModuleMapper layoutModuleMapper;
    @Autowired
    private LaserModuleMapper laserModuleMapper;
    @Autowired
    private SortingModuleMapper sortingModuleMapper;
    // 处理文件上传的接口
    @PostMapping("/process-pdf")
    public R handlePdf(@RequestParam MultipartFile file) throws IOException {
        // 验证文件唯一性
        String fileName = file.getOriginalFilename();
        //1. 创建文件夹
        String folderName = fileName.replace(".pdf", "").replaceAll("(?<=\\S) +(?=\\S)", "").trim();
        Path parentPath = Paths.get("D:/tempFiles/");
        Path folderPath = parentPath.resolve(folderName);
        Files.createDirectories(folderPath);
        List<LaserModule> laserModules = new ArrayList<>();
        List<SortingModule> sortingModules = new ArrayList<>();
        // 2. 加载PDF并处理
        try (PDDocument document = PDDocument.load(file.getInputStream())) {
            PDFTextStripper stripper = new PDFTextStripper();
            int totalPages = document.getNumberOfPages();
            //保存数据至排版模块表中
            Calendar calendar = Calendar.getInstance();
            // 转换为Date类型
            Date currentDate = calendar.getTime();
            LayoutModule layoutModule = new LayoutModule();
            // 创建ID生成器（数据中心ID=1，机器ID=1）
            SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
            long id = idGenerator.nextId();
            layoutModule.setId(id);
            layoutModule.setApplicationName(folderName);
            layoutModule.setCompletionTime(currentDate);
            layoutModuleMapper.insertData(layoutModule);
            for (int pageNum = 1; pageNum <= totalPages; pageNum++) {
                // 提取当前页文本
                stripper.setStartPage(pageNum);
                stripper.setEndPage(pageNum);
                String pageText = stripper.getText(document);
                // 3. 提取字段（适配文档表格格式，如{insert\_element\_1\_}、{insert\_element\_2\_}等）
                Map<String, String> fields = ExtractFile.extractFields(pageText);
                String programName = fields.getOrDefault("程序名称", "page_" + pageNum);
                //保存数据至激光表中
                LaserModule laserModule = new LaserModule();
                laserModule.setApplicationName(fields.get("程序名称"));
                laserModule.setBoardType(fields.get("材料型号"));
                laserModule.setPlateThickness(fields.get("材料厚度"));
                laserModule.setRunsNum(Integer.parseInt(fields.get("运行次数")));
                laserModule.setReceptionTime(currentDate);
                laserModule.setLayId(layoutModule.getId());
                laserModule.setCompleted("未完成");

                SortingModule sortingModule = new SortingModule();
                sortingModule.setApplicationName(fields.get("程序名称"));
                sortingModule.setBoardType(fields.get("材料型号"));
                sortingModule.setPlateThickness(fields.get("材料厚度"));
                sortingModule.setRunsNum(Integer.parseInt(fields.get("运行次数")));
                sortingModule.setSortingCompleted("未完成");
                // 4. 拆分并保存当前页
                PDPage page = document.getPage(pageNum - 1);
                try (PDDocument singlePageDoc = new PDDocument()) {
                    singlePageDoc.addPage(page);
                    String savePath = folderPath + File.separator + programName + ".pdf";
                    String path = savePath.replaceAll("(?<=\\S) +(?=\\S)", "").trim();
                    String filesPath = path.replace("\\","/").replace("D:/tempFiles/","http://localhost:8080/static-pdfs/");
                    singlePageDoc.save(path);
                    laserModule.setAttachmentAddress(filesPath);
                    laserModules.add(laserModule);
                    sortingModule.setAttachmentAddress(filesPath);
                    sortingModules.add(sortingModule);
                }

                // 输出提取的字段（可根据需求持久化）
                System.out.println("页面" + pageNum + "字段：" + fields);
            }
            laserModuleMapper.batchList(laserModules);
            sortingModuleMapper.batchList(sortingModules);
        }
        return R.ok("上传成功");
    }
}